package com.ecric.http.OkHttp3.package3;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 04/04/2018 16:54
 * <h3>Copyright</h3> Copyright (c)2018 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class RequestCall {

    private  Request request ;
    private Handler handler;
    public RequestCall (Request request){
        this.request = request;
        handler = new Handler(Looper.getMainLooper());
    }


    public void enqueue (final RequestCallback callback){
        callback.onBefore();
        OkHttpsUtil.getInstance().getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(request,e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) {
                if (response.isSuccessful()){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onResponse(response);
                        }
                    });
                }else {
                    try {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(response,response.code());
                            }
                        });
                    }catch (final Exception e){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(response,response.code());
                            }
                        });
                    }
                }
            }
        });
    }


}
